package net.bwie.vehicle.dws.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.guanjuntao.util.DateTimeUtil;
import net.bwie.realtime.guanjuntao.util.JdbcUtil;
import net.bwie.realtime.guanjuntao.util.KafkaUtil;
import net.bwie.vehicle.dws.bean.CarBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 实时在线车辆数
 * @Author: FuHe
 * @Date: 2025/5/28
 */
public class VehicleVinCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "car-vehicle-data");
//        kafkaStream.print();
//        DataStream<Integer> vinCountStream = processheadel(kafkaStream);
        DataStream<String> processheadel = processheadel(kafkaStream);
        processheadel.print();
        JdbcUtil.sinkToClickhouseUpsert(processheadel,"INSERT INTO new_car.vehicle_count (window_start, window_end, vin_count)\n" +
                "VALUES (?, ?, ?)");


        env.execute("VehicleRealtimeVinCount");
    }

    private static DataStream<String> processheadel(DataStream<String> kafkaStream) {
        SingleOutputStreamOperator<CarBean> vehicleData = kafkaStream.map(o -> JSON.parseObject(o, CarBean.class));
        SingleOutputStreamOperator<CarBean> vehicleDataSingleOutputStreamOperator = vehicleData.assignTimestampsAndWatermarks(WatermarkStrategy
                .<CarBean>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(
                        new SerializableTimestampAssigner<CarBean>() {
                            @Override
                            public long extractTimestamp(CarBean element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        }
                )
        );
        DataStream<String> process = vehicleDataSingleOutputStreamOperator
                .map(o -> 1)
                .windowAll(TumblingEventTimeWindows.of(Time.minutes(1)))
                .process(
                        new ProcessAllWindowFunction<Integer, String, TimeWindow>() {
                            @Override
                            public void process(Context context, Iterable<Integer> elements, Collector<String> out) throws Exception {
                                int sum = 0;
                                for (Integer element : elements) {
                                    sum += element;
                                }
                                // 获取窗口开始时间
                                String windowStart = DateTimeUtil.convertLongToString(context.window().getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                                String windowEnd = DateTimeUtil.convertLongToString(context.window().getEnd(), DateTimeUtil.DATE_TIME_FORMAT);
                                out.collect(windowStart+","+windowEnd+","+sum);
                            }
                        }
                );
        return process;
    }
}
